package com.winhxd.b2c.order.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.winhxd.b2c.common.domain.PagedList;
import com.winhxd.b2c.common.domain.order.condition.OrderAfterSaleCondition;
import com.winhxd.b2c.common.domain.order.condition.OrderBaseConditions;
import com.winhxd.b2c.common.domain.order.condition.OrderDetailsCondition;
import com.winhxd.b2c.common.domain.order.condition.OrderQueryCondition;
import com.winhxd.b2c.common.domain.order.model.OrderConsigneeMessage;
import com.winhxd.b2c.common.domain.order.model.OrderInfo;
import com.winhxd.b2c.common.domain.order.model.OrderProductAttribute;
import com.winhxd.b2c.common.domain.order.vo.OrderDetailForCustomerVO;
import com.winhxd.b2c.common.domain.order.vo.OrderDetailVO;
import com.winhxd.b2c.common.domain.order.vo.OrderInfoAfterSaleVO;
import com.winhxd.b2c.common.domain.order.vo.OrderInfoVO;
import com.winhxd.b2c.common.util.JsonUtil;
import com.winhxd.b2c.order.dao.*;
import com.winhxd.b2c.order.service.OrderQueryService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Supplier;
import java.util.stream.Collectors;

/**
 * @author zhangshuguang
 * @version 1.0
 * @date 2019/1/8、14:24
 * @Description
 */
@Service
public class OrderQueryServiceImpl implements OrderQueryService {
    private static final Logger logger = LoggerFactory.getLogger(OrderPayServiceImpl.class);
    @Autowired
    private OrderInfoMapper orderInfoMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private OrderProductAttributeMapper orderProductAttributeMapper;
    @Autowired
    private OrderConsigneeMessageMapper orderConsigneeMessageMapper;
    @Autowired
    private OrderAfterSaleMapper orderAfterSaleMapper;

    private String logUrl = "/api-order/order/4401/v1/getOrderList";

    @Override
    public PagedList<OrderInfoVO> findOrderList(OrderBaseConditions condition) {
        PagedList<OrderInfoVO> result = new PagedList<>();
        PageHelper.startPage(condition.getPageNo(),condition.getPageSize());
        List<OrderInfoVO> orderInfoVOList = orderInfoMapper.selectOrderInfoListByCondition(condition);
        logger.info(logUrl+"-C端查询订单列表用户id:"+condition.getCustomerId()+"--查询订单主表-开始");
        //订单号集合
        List<String> orderList = new ArrayList<>();
        //代发货订单集合
        if(CollectionUtils.isEmpty(orderInfoVOList)){
            logger.info(logUrl+"-C端查询订单列表用户id:"+condition.getCustomerId()+"--查询订单主表数据为空！！！");
            return null;
        }
        orderList = orderInfoVOList.stream().map(OrderInfoVO::getOrderNo).collect(Collectors.toList());
        //根据订单号集合查询订单详情
        Map<String,List<OrderDetailVO>> orderDetailMap =  this.selectOrderDetailByOrderList(orderList);
        if(!CollectionUtils.isEmpty(orderInfoVOList)){
            orderInfoVOList.forEach(orderInfoVO -> {
                orderInfoVO.setOrderDetailVOList(orderDetailMap.get(orderInfoVO.getOrderNo()));
            });
        }

        //根据订单号集合查询订单退款信息（待发货订单）
        Map<String,OrderInfoAfterSaleVO> orderAfterSaleMap = this.selectOrderAfterSaleByOrderList(orderList);
        if(!CollectionUtils.isEmpty(orderAfterSaleMap)){
            orderInfoVOList.forEach(orderInfoVO -> {
                orderInfoVO.setOrderAfterSale(orderAfterSaleMap.get(orderInfoVO.getOrderNo()));
            });
        }
        //根据订单号集合查询收货人信息
       // Map<String,List<OrderConsigneeMessageVO>> orderConsigneeMessageMap = this.selectOrderConsigneeMessageByOrderList(orderList);


        PageInfo pageInfo = new PageInfo(orderInfoVOList);
        result.setPageNo(condition.getPageNo());
        result.setPageSize(condition.getPageSize());
        result.setData(orderInfoVOList);
        result.setTotalRows(pageInfo.getTotal());
        logger.info(logUrl+"-C端查询订单列表用户id:"+condition.getCustomerId()+"--查询订单主表-结束");
        return result;
    }


    /**
     * 根据订单编号查询所有售后信息（以订单为维度）
     * @param orderNoList
     * @return
     */
    private Map<String, OrderInfoAfterSaleVO> selectOrderAfterSaleByOrderList(List<String> orderNoList) {
        Map<String, OrderInfoAfterSaleVO> map = new HashMap<>();
        List<OrderInfoAfterSaleVO> list = orderAfterSaleMapper.selectOrderAfterSaleByOrderList(orderNoList);
        if(CollectionUtils.isEmpty(list)){
           return  map;
        }

        Supplier<OrderInfoAfterSaleVO> afterSaleVOSupplier = OrderInfoAfterSaleVO::new;
        orderNoList.forEach(orderNos ->{
            OrderInfoAfterSaleVO afterSaleVO = afterSaleVOSupplier.get();
            afterSaleVO = list.stream().filter(vo -> vo.getOrderNo().equals(orderNos)).collect(Collectors.toList()).get(0);
            map.put(orderNos,afterSaleVO);
        });
        return map;
    }

    @Override
    public PagedList<OrderInfoVO> selectOrderAllInfo(OrderQueryCondition condition) {
        logger.info(logUrl+"-C端查询订单列表用户id:"+condition.getCustomerId()+"--查询订单主表-开始");
        PagedList<OrderInfoVO> result = new PagedList<>();
        int pageNo = condition.getPageNo();
        int pageSize = condition.getPageSize();
        result.setPageNo(pageNo);
        result.setPageSize(pageSize);
        condition.setPageNo((pageNo -1 )*pageSize);
        //根据条件查询订单总条数（分页用）
        List<OrderInfoVO> orderInfoVOList = orderInfoMapper.selectOrderListByCondition(condition);
        List<String> orderNoList = orderInfoVOList.stream().map(OrderInfoVO::getOrderNo).collect(Collectors.toList());
        List<OrderInfoVO> rList = new ArrayList<>();
        if(!CollectionUtils.isEmpty(orderInfoVOList)){
            condition.setOrderNoList(orderNoList);
            rList = orderInfoMapper.selectOrderAllInfo(condition);
        }
        result.setData(rList);
        logger.info(logUrl+"-C端查询订单列表用户id:"+condition.getCustomerId()+"--查询订单主表-结束");
        return result;
    }

    @Override
    public PagedList<OrderInfoVO> selectOrderAllInfoV3(OrderQueryCondition condition) {
        logger.info(logUrl+"-C端查询订单列表用户id:"+condition.getCustomerId()+"--查询订单主表-开始");
        PagedList<OrderInfoVO> result = new PagedList<>();
        int pageNo = condition.getPageNo();
        int pageSize = condition.getPageSize();
        result.setPageNo(pageNo);
        result.setPageSize(pageSize);
        condition.setStartNum((pageNo -1 )*pageSize);
        List<OrderInfoVO> rList = orderInfoMapper.selectOrderAllInfo(condition);
        result.setData(rList);
        logger.info(logUrl+"-C端查询订单列表用户id:"+condition.getCustomerId()+"--查询订单主表-结束");
        return result;
    }

    /**
     * @author hjw
     * @date 2019/1/10 17:49
     * @param condition
     * @Description 查询订单明细所有信息
     * @return
     */
    @Override
    public OrderInfoVO selectOrderDetailAllInfo(OrderQueryCondition condition){
        //取消分页
        condition.setPageNo(0);
        List<OrderInfoVO> list = orderInfoMapper.selectOrderAllInfo(condition);
        if(org.apache.commons.collections4.CollectionUtils.isNotEmpty(list)){
            return list.get(0);
        }
        logger.info("-C端查询订单明细用户id:"+condition.getCustomerId()+"--查询订单没有数据");
        return null;
    }

    @Override
    public OrderDetailForCustomerVO getOrderDetailByOrder(OrderDetailsCondition condition) {
        OrderDetailForCustomerVO vo = new OrderDetailForCustomerVO();
        //获取订单信息
        OrderInfo orderInfo = orderInfoMapper.selectByOrderNo(condition.getOrderNo());
        vo.setOrderInfo(orderInfo);
        //获取订单详情
        OrderAfterSaleCondition afterSaleCondition = new OrderAfterSaleCondition();
        afterSaleCondition.setOrderNo(condition.getOrderNo());
        List<OrderDetailVO> orderDetailVOList = orderDetailMapper.selectOrderDetailByCondition(afterSaleCondition);
        vo.setOrderDetailVOList(orderDetailVOList);
        // 获取收货信息
        OrderConsigneeMessage orderConsigneeMessage = orderConsigneeMessageMapper.selectByOrderNo(condition.getOrderNo());
        vo.setOrderConsigneeMessage(orderConsigneeMessage);
        return vo;
    }

    private Map<String, List<OrderDetailVO>> selectOrderDetailByOrderList(List<String> orderNoList) {
        Map<String, List<OrderDetailVO>> map = new HashMap<>();
        OrderAfterSaleCondition condition = new OrderAfterSaleCondition();
        condition.setOrderNoList(orderNoList);
        List<OrderDetailVO> orderDetailVOList = orderDetailMapper.selectOrderDetailByCondition(condition);
        List<Long> orderDetailIdList = new ArrayList<>();
        if(CollectionUtils.isEmpty(orderDetailVOList)){
            logger.info(logUrl+"-C端查询订单列表--根据订单编码列表批量查询订单明细数据为空！！！");
            return map;
        }
        orderDetailIdList = orderDetailVOList.stream().map(OrderDetailVO::getId).collect(Collectors.toList());
        Map<Long, List<OrderProductAttribute>> attributeMap = this.selectAttributeByProduIds(orderDetailIdList);
        orderDetailVOList.forEach(orderDetailVO -> {
            orderDetailVO.setAttributes(attributeMap.get(orderDetailVO.getId()));
        });
        orderNoList.forEach(orderNos -> {
            List<OrderDetailVO> listDetail = orderDetailVOList.stream().filter(detailVO -> detailVO.getOrderNo().equals(orderNos)).collect(Collectors.toList());
            map.put(orderNos,listDetail);
        });
        return map;
    }

    private Map<Long, List<OrderProductAttribute>> selectAttributeByProduIds(List<Long> orderDetailIdList) {
        Map<Long, List<OrderProductAttribute>> map = new HashMap<>();
        List<OrderProductAttribute> orderProductAttributeList = orderProductAttributeMapper.selectAttributeByProduIds(orderDetailIdList);
        if(!CollectionUtils.isEmpty(orderProductAttributeList)){
            orderDetailIdList.forEach(orderDetailIds ->{
                List<OrderProductAttribute> orderProductAttribute = orderProductAttributeList.stream().filter(productAttribute -> productAttribute.getOrderProdectInfoId().equals(orderDetailIds)).collect(Collectors.toList());
                map.put(orderDetailIds,orderProductAttribute);
            });
        }
        return map;
    }
}
